package com.ujs.aclservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ujs.aclservice.entity.Permission;
import com.ujs.aclservice.entity.RolePermission;
import com.ujs.aclservice.entity.User;
import com.ujs.aclservice.helper.MemuHelper;
import com.ujs.aclservice.helper.PermissionHelper;
import com.ujs.aclservice.mapper.PermissionMapper;
import com.ujs.aclservice.service.PermissionService;
import com.ujs.aclservice.service.RolePermissionService;
import com.ujs.aclservice.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private UserService userService;


    // 根据角色获取菜单
    @Override
    public List<Permission> selectAllMenu(String roleId) {
        List<Permission> allPermissionList = baseMapper.selectList(new QueryWrapper<Permission>().orderByAsc("CAST(id AS SIGNED)"));

        // 根据角色id获取角色权限
        List<RolePermission> rolePermissionList = rolePermissionService.list(new QueryWrapper<RolePermission>().eq("role_id", roleId));
        for (Permission permission : allPermissionList) {
            for (RolePermission rolePermission : rolePermissionList) {
                if (rolePermission.getPermissionId().equals(permission.getId())) {
                    permission.setSelect(true);
                }
            }
        }


        return bulid(allPermissionList);
    }


    // 根据用户id获取用户菜单
    @Override
    public List<String> selectPermissionValueByUserId(String id) {

        List<String> selectPermissionValueList = null;
        if (this.isSysAdmin(id)) {
            // 如果是系统管理员，获取所有权限
            selectPermissionValueList = baseMapper.selectAllPermissionValue();
        } else {
            selectPermissionValueList = baseMapper.selectPermissionValueByUserId(id);
        }
        return selectPermissionValueList;
    }

    @Override
    public List<JSONObject> selectPermissionByUserId(String userId) {
        List<Permission> selectPermissionList = null;
        if (this.isSysAdmin(userId)) {
            // 如果是超级管理员，获取所有菜单
            selectPermissionList = baseMapper.selectList(null);
        } else {
            selectPermissionList = baseMapper.selectPermissionByUserId(userId);
        }

        List<Permission> permissionList = PermissionHelper.bulid(selectPermissionList);
        return MemuHelper.bulid(permissionList);
    }

    /**
     * 判断用户是否系统管理员
     *
     * @param userId
     * @return
     */
    private boolean isSysAdmin(String userId) {
        User user = userService.getById(userId);
        if (null != user && "admin".equals(user.getUsername())) {
            return true;
        }
        return false;
    }


    /**
     * 使用递归方法建菜单
     *
     * @param treeNodes
     * @return
     */
    private static List<Permission> bulid(List<Permission> treeNodes) {
        List<Permission> trees = new ArrayList<>();
        for (Permission treeNode : treeNodes) {
            if ("0".equals(treeNode.getPid())) {
                treeNode.setLevel(1);
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    private static Permission findChildren(Permission treeNode, List<Permission> treeNodes) {
        treeNode.setChildren(new ArrayList<>());

        for (Permission it : treeNodes) {
            if (treeNode.getId().equals(it.getPid())) {
                int level = treeNode.getLevel() + 1;
                it.setLevel(level);
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }



    @Override
    public List<Permission> queryAllMenuGuli() {
        // 1.查询所有菜单数据
        QueryWrapper<Permission> wrapper = new QueryWrapper<Permission>().orderByDesc("id");
        List<Permission> permissions = baseMapper.selectList(wrapper);
        // 把菜单list集合进行封装
        return buildPermission(permissions);
    }

    @Override
    public void removeChildByIdGuli(String id) {
        // 查询出所有的数据。
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        List<Permission> permissionList = baseMapper.selectList(wrapper);
        // 封装所有需要删除的id
        List<String> ids = buildIds(id, permissionList);
        ids.add(id);
        System.out.println("ids====================" + ids);
        // baseMapper.deleteBatchIds(ids);
    }

    @Override
    public void saveRolePermissionRelationShipGuli(String roleId, String[] permissionId) {
        List<RolePermission> permissionList = new ArrayList<>();
        for (String perId : permissionId) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(perId);
            permissionList.add(rolePermission);
        }
        rolePermissionService.saveBatch(permissionList);
    }

    private List<String> buildIds(String id, List<Permission> permissionList) {
        // 查出所有id对应的pid
        ArrayList<String> ids = new ArrayList<>();
        for (Permission permission : permissionList) {
            if (id.equals(permission.getPid())) {
                ids.addAll(buildIds(permission.getId(), permissionList));
                ids.add(permission.getId());
            }
        }
        return ids;
    }


    public List<Permission> buildPermission(List<Permission> permissions) {
        List<Permission> finalNode = new ArrayList<>();
        for (Permission permission : permissions) {
            if ("0".equals(permission.getPid())) {
                // 找到顶层数据
                permission.setLevel(1);
                // 根据顶层菜单，向里面继续查询子菜单，封装到finalNode里面
                finalNode.add(selectChildren(permission, permissions));
            }
        }
        return finalNode;
    }

    private Permission selectChildren(Permission permission, List<Permission> permissionList) {
        // 要向一层菜单里面放二层菜单，把对象初始化
        permission.setChildren(new ArrayList<>());
        for (Permission it : permissionList) {
            // 判断一级节点的id和二级节点的pid是否相同
            if (it.getPid().equals(permission.getId())) {
                // 把父菜单的level值 +1
                int level = permission.getLevel() + 1;
                it.setLevel(level);
                // 把查询出来的子菜单放到父菜单里面
                permission.getChildren().add(selectChildren(it, permissionList));
            }
        }
        return permission;
    }
}
